/**
 * 
 */
package de.gee.erep.client.ui.presenter;

import java.util.ArrayList;

import com.google.gwt.user.client.rpc.AsyncCallback;

import de.gee.erep.client.Environment;
import de.gee.erep.client.calls.rpc.CitizenServiceAsync;
import de.gee.erep.client.calls.rpc.InitializationAsync;
import de.gee.erep.client.calls.rpc.callbacks.GotCitizenDetails;
import de.gee.erep.client.ui.displays.CitizenDisplay;
import de.gee.erep.shared.entities.citizen.Citizen;
import de.gee.erep.shared.entities.citizen.CitizenDetail;
import de.gee.erep.shared.entities.citizen.CitizenDetailId;
import de.gee.erep.shared.rpctypes.action.impls.GetCitizenDetails;

/**
 * @author Matthew Gee created: 09.05.2011
 */
public class CitizenPresenter extends Presenter<CitizenDisplay> {
	/***/
	private static final int DEFAULT_NO_OF_ITEMS = 10;
	/***/
	private int noOfItems = 0;
	/***/
	private static final int GERMANY = 12;
	/** LaunchKey. */
	public static final String PLACE = "citizen";

	/**
	 * @param display
	 *            d
	 * @param env
	 *            e
	 * @param params
	 *            p
	 */
	public CitizenPresenter(final CitizenDisplay display, final Environment env, final String params) {
		super(display, env, params);
		setInitialData();
	}

	/**
	 * 
	 */
	private void setInitialData() {
		InitializationAsync remoteInitService = super.getEnvironment().getModel().getRemoteInitService();
		remoteInitService.getCitizenOf(GERMANY, new AsyncCallback<ArrayList<Citizen>>() {
			@Override
			public void onSuccess(final ArrayList<Citizen> result) {
				CitizenPresenter.super.getDisplay().setData(result);
				int from = 0;
				int count = (getNoOfItems() != 0) && (getNoOfItems() > 0) ? getNoOfItems() : DEFAULT_NO_OF_ITEMS;
				getDetails(detailsFor(result, count, from));
			}

			@Override
			public void onFailure(final Throwable caught) {
				// do something genius
			}
		});
	}

	private ArrayList<Citizen> detailsFor(ArrayList<Citizen> result, int count, int from)
			throws ArrayIndexOutOfBoundsException {
		if (result.size() > from + count) {
			return new ArrayList<Citizen>(result.subList(from, from + count));
		}
		return null;
	}

	/**
	 * 
	 * @param list
	 *            l
	 */
	private void getDetails(final ArrayList<Citizen> list) {
		CitizenServiceAsync service = super.getEnvironment().getModel().getCitizenService();

		ArrayList<CitizenDetailId> details = new ArrayList<CitizenDetailId>();
		for (Citizen c : list) {
			details.addAll(c.getDetailIds());
		}
		service.execute(new GetCitizenDetails(details), new GotCitizenDetails() {

			@Override
			public void got(final ArrayList<CitizenDetail> details) {
				for (CitizenDetail d : details) {
					System.out.println(d);
				}
			}
		});
	}

	/**
	 * @param noOfItems
	 *            the noOfItems to set
	 */
	public final void setNoOfItems(final int noOfItems) {
		this.noOfItems = noOfItems;
	}

	/**
	 * @return the noOfItems
	 */
	public final int getNoOfItems() {
		return noOfItems;
	}
}
